import jieba
from matplotlib import pylab as plt
from wordcloud import WordCloud
import numpy as np
from PIL import Image
from utils.querymysql import querymysql

def get_img1(targetImageSrc,resImageSrc):
    data = querymysql('SELECT workTag FROM jobData',[],'select')
    # 定义停用词
    stop_words = {'专业',}
    
    #分词
    text = ''
    for item in data:
        if item['workTag'] and item['workTag'].strip():  # 确保workTag存在且不为空
            text += item['workTag'] + ' '
            
    data_cut = jieba.cut(text, cut_all=False)
    # 过滤停用词
    words = [word for word in data_cut if word.strip() and word not in stop_words]
    string = ' '.join(words)

    if not string.strip():  # 检查是否有文本内容
        print("警告：没有找到有效的文本内容用于生成词云")
        return

    #词云图
    img = Image.open(targetImageSrc)
    img_arr = np.array(img)
    wc = WordCloud(
        font_path='static/static/font/STHupo.ttf',
        mask=img_arr,
        background_color='#fff',
        width=800,
        height=800,
        min_font_size=10,
        max_font_size=150
    )
    wc.generate_from_text(string)

    #图片生成
    plt.figure(figsize=(10, 10))
    plt.imshow(wc)
    plt.axis('off')
    plt.savefig(resImageSrc, dpi=300, bbox_inches='tight', pad_inches=0)
    plt.close()

def get_img2(targetImageSrc,resImageSrc):
    data = querymysql('SELECT title FROM jobData',[],'select')
    # 定义停用词
    stop_words = {'工程师'}
    
    #分词
    text = ''
    for item in data:
        if item['title'] and item['title'].strip():  # 确保title存在且不为空
            text += item['title'] + ' '
            
    data_cut = jieba.cut(text, cut_all=False)
    # 过滤停用词
    words = [word for word in data_cut if word.strip() and word not in stop_words]
    string = ' '.join(words)

    if not string.strip():  # 检查是否有文本内容
        print("警告：没有找到有效的文本内容用于生成词云")
        return

    #词云图
    img = Image.open(targetImageSrc)
    img_arr = np.array(img)
    wc = WordCloud(
        font_path='static/static/font/STHupo.ttf',
        mask=img_arr,
        background_color='#fff',
        width=800,
        height=800,
        min_font_size=10,
        max_font_size=150
    )
    wc.generate_from_text(string)

    #图片生成
    plt.figure(figsize=(10, 10))
    plt.imshow(wc)
    plt.axis('off')
    plt.savefig(resImageSrc, dpi=300, bbox_inches='tight', pad_inches=0)
    plt.close()

# 生成词云图
get_img1('./static/static/cloudImg/tree1.jpg','./static/static/tagCloud')
get_img2('./static/static/cloudImg/love.png','./static/static/titleCloud')